package cn.silver.module.authority.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.silver.framework.log.annotation.Log;
import cn.silver.framework.log.enums.OperateEnums;
import cn.silver.framework.mybatis.controller.DataController;
import cn.silver.framework.openapi.model.Result;
import cn.silver.framework.tenant.helper.TenantHelper;
import cn.silver.module.authority.domain.SysTenant;
import cn.silver.module.authority.bean.TenantBean;
import cn.silver.module.authority.param.TenantParam;
import cn.silver.module.authority.service.ISysTenantService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 租户管理
 *
 * @author Silver Zhou
 */
@Validated
@RestController
@RequiredArgsConstructor
@Tag(name = "权限管理-租户管理")
@RequestMapping("/system/tenant")
public class SysTenantController extends DataController<ISysTenantService, SysTenant, TenantParam, TenantBean> {

    private final ISysTenantService tenantService;

    @Override
    @Resource
    public void setBaseService(ISysTenantService baseService) {
        this.baseService = baseService;
        this.setTitle("权限管理-租户管理");
        this.setCode("authority:tenant");
    }

    /**
     * 动态切换租户
     *
     * @param tenantId 租户ID
     */
    @GetMapping("/dynamic/{tenantId}")
//    @SaCheckRole(TenantConstants.SUPER_ADMIN_ROLE_KEY)
    public Result<Void> dynamicTenant(@NotBlank(message = "租户ID不能为空") @PathVariable String tenantId) {
        TenantHelper.setDynamic(tenantId);
        return Result.ok();
    }

    /**
     * 清除动态租户
     */
    @GetMapping("/dynamic/clear")
//    @SaCheckRole(TenantConstants.SUPER_ADMIN_ROLE_KEY)
    public Result<Void> dynamicClear() {
        TenantHelper.clearDynamic();
        return Result.ok();
    }


    /**
     * 同步租户套餐
     *
     * @param tenantId  租户id
     * @param packageId 套餐id
     */
    @GetMapping("/syncTenantPackage")
    @SaCheckPermission("system:tenant:sync")
    @Log(title = "租户", operate = OperateEnums.ALTER_SYNC)
//    @SaCheckRole(TenantConstants.SUPER_ADMIN_ROLE_KEY)
    public Result<Void> syncTenantPackage(@NotBlank(message = "租户ID不能为空") String tenantId,
                                          @NotNull(message = "套餐ID不能为空") String packageId) {
        TenantHelper.ignore(() -> tenantService.syncTenantPackage(tenantId, packageId));
        return Result.ok();
    }

}
